import pandas as pd
import numpy as np
import copy
import matplotlib.pyplot as plt


class DrawPicture:
    ContainerChangeLocationList = []
    ContainerChangeLocationTimeList = []

    def __init__(self):
        self.ani = None
        self.DeviceSC = None
        self.ContainerSC1 = None
        self.ContainerSC2 = None
        self.ChangeDict = {}
        plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
        plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)
        self.text = self.ax.text(0, 14, "时间点: %d" % 0)
        self.ax.set_xlim(1, 67)
        self.ax.set_ylim(1, 14)
        self.xtick = range(0, 67)
        self.ytick = range(0, 15)
        self.ax.set_xticks(self.xtick)
        self.ax.set_yticks(self.ytick)
        self.ax.grid(True)
        self.ax.set_aspect(1)
        self.ax.set_xlabel("贝位")
        self.ax.set_ylabel("栈位")
        self.ax.set_title("集装箱堆场")
        self.Locationlist1 = []
        self.Locationlist2 = []
        self.StateColor = {-2: 'yellow', -1: 'blue', 0: 'yellow', 1: 'green', 2: 'black', 3: 'red', 4: 'black',
                           5: 'aquamarine'}
        # 集装箱散点图一层图层
        self.ContainerSC1 = self.ax.scatter([], [], s=100, marker='s', alpha=1, c='orange')
        self.ContainerSC2 = self.ax.scatter([], [], s=100, marker='s', alpha=1, c='brown')
        # self.init_containerlocation()

    def Draw(self, ContainerLocationInit):
        # 创建一个 66*15 的网格
        x = np.arange(1, 67)
        y = np.arange(1, 15)
        X, Y = np.meshgrid(x, y)
        # 查找一层现有集装箱位置
        index = np.where(ContainerLocationInit[0][:][:] == 1)
        indices_to_remove = list(zip(index[0], index[1]))
        # 创建布尔索引
        mask = np.zeros(X.shape, dtype=bool)
        for index in indices_to_remove:
            mask[index[0], index[1]] = True
        # 应用布尔索引移除值
        X_masked = X[mask]
        Y_masked = Y[mask]
        # 将网格展平为一维数组
        x_flattened = X_masked.flatten()
        y_flattened = Y_masked.flatten()
        self.ContainerSC1.set_offsets(np.c_[x_flattened, y_flattened])
        # 查找二层现有集装箱位置
        index = np.where(ContainerLocationInit[1][:][:] == 1)
        indices_to_remove = list(zip(index[0], index[1]))
        # 创建布尔索引
        mask = np.zeros(X.shape, dtype=bool)
        for index in indices_to_remove:
            mask[index[0], index[1]] = True
        # 应用布尔索引移除值
        X_masked = X[mask]
        Y_masked = Y[mask]
        # 将网格展平为一维数组
        x_flattened = X_masked.flatten()
        y_flattened = Y_masked.flatten()
        self.ContainerSC2.set_offsets(np.c_[x_flattened, y_flattened])


class ContainerLocation:
    ContainerList = dict()

    def __init__(self, bay, stack, level, state, Locationtype):
        self.bay = bay  # 贝位
        self.level = level  # 层位
        self.stack = stack  # 栈位
        self.state = state  # 集装箱箱位状态: 放置货物 1 没有货物 0
        self.Locationtype = Locationtype  # 箱位类型: 0 普通箱位 1 道路箱位
        key = f"{bay}-{stack}-{level}"
        value = self
        ContainerLocation.ContainerList[key] = value

    @classmethod
    def FindContainerLocation(cls, bay, stack, level):
        key = f"{bay}-{stack}-{level}"
        return ContainerLocation.ContainerList[key]


if __name__ == "__main__":
    # 读取堆场货位数据
    Container_data = pd.read_excel('箱位状态表(20240320目前可用).xlsx')
    # 生成货位数据
    for index, item in Container_data.iterrows():
        ContainerLocation(item['贝位'], item['栈位'], item['层位'], 0, item['位置类型'])
        if item['位置类型'] == 0 and item['层位'] == 1:
            SelectContainerLocation = ContainerLocation.FindContainerLocation(item['贝位'], item['栈位'], item['层位'])
            SelectContainerLocation.state = np.random.choice([0, 1], p=[0.5, 0.5])
            item['占用状态'] = SelectContainerLocation.state
        if item['位置类型'] == 0 and item['层位'] == 2:
            SelectContainerLocation = ContainerLocation.FindContainerLocation(item['贝位'], item['栈位'], item['层位'])
            if ContainerLocation.FindContainerLocation(item['贝位'], item['栈位'], 1).state == 0:
                SelectContainerLocation.state = 0
                item['占用状态'] = SelectContainerLocation.state
            else:
                SelectContainerLocation.state = np.random.choice([0, 1], p=[0.5, 0.5])
                item['占用状态'] = SelectContainerLocation.state
        if item['位置类型'] == 1:
            SelectContainerLocation = ContainerLocation.FindContainerLocation(item['贝位'], item['栈位'], item['层位'])
            SelectContainerLocation.state = 0
            item['占用状态'] = SelectContainerLocation.state
    HTArray = np.zeros((2, 14, 66))
    for key, value in ContainerLocation.ContainerList.items():
        bay, stack, level = key.split('-')
        HTArray[int(level) - 1, int(stack) - 1, int(bay) - 1] = value.state
    DrawPicture_ = DrawPicture()
    DrawPicture_.Draw(HTArray)
    # 保存箱位状态表
    Container_data.to_excel('箱位状态表(新).xlsx', index=False)
    # 展示箱位状态图
    plt.show()
